﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AuthApi.Contracts;

namespace WebAppAuthAdmin.Code
{
    public class AppContext
    {
        private static AppContext _instance = new AppContext();

        public static AppContext Instance
        {
            get { return _instance;  }
        }

        public Company GetSingleCompanyContext(HttpContext context)
        {
            return GetCompanyContext(context).SingleOrDefault();
        }

        public List<Company> GetCompanyContext(HttpContext context)
        {
            List<Company> companyList = null;
            const string companyContextKey = "companyContextKey";
            const string companyContextCookieKey = "companyContextCookieKey";

            companyList = context.Session[companyContextKey] as List<Company>;
            if (companyList == null)
            {               
                // Obtengo los valores de una cookie
                List<string> cookieIds = HttpHelper.GetCookieValues(companyContextCookieKey, context.Request);
                if (cookieIds.Count > 0)
                {
                    var allCompanyList = WebServiceHelper.GetCompanyList(string.Empty);
                    var cookiesIdsInt = cookieIds.Where(c=> c != string.Empty).Select(c => Convert.ToInt32(c)).ToList();
                    companyList = allCompanyList.Where(c => cookiesIdsInt.Contains(c.Id)).ToList();
                }
                else
                {
                    companyList = new List<Company>();
                }
            }

            return companyList;
        }

        public void SetCompanyContext(HttpContext context, List<Company> companyList)
        {            
            const string companyContextKey = "companyContextKey";
            const string companyContextCookieKey = "companyContextCookieKey";

            context.Session[companyContextKey] = companyList;
            string[] ids = companyList.Select(c => c.Id.ToString()).ToArray();
            HttpHelper.SetCookieValues(companyContextCookieKey, context.Response, ids);            
        }
    }
}